package api

import (
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"zsc-boot/app/customer/model"
	"zsc-boot/app/customer/model/request"
	"zsc-boot/app/customer/service"
	layerModel "zsc-boot/app/system_layer/model"
	service2 "zsc-boot/app/system_layer/service"
	"zsc-boot/core"
	"zsc-boot/core/orm"
	"zsc-boot/core/web"
)

type OrderApi struct {
	svc *service.OrderSvc
}

func NewOrderApi() *OrderApi {
	return &OrderApi{svc: new(service.OrderSvc)}
}

func (o *OrderApi) AllList(ctx *gin.Context) {
	var req request.OrderMyListReq
	_ = ctx.BindQuery(&req)

	var (
		userId   = service2.GetUserID(ctx)
		userInfo layerModel.ServiceUser
		err      error
	)
	userId = service2.GetUserID(ctx)
	if userInfo, err = orm.Detail[layerModel.ServiceUser](userId, "Role"); err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}

	list, count, NotMoney, Money, err := o.svc.AllList(req, userInfo)
	if err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	}
	web.SuccessResponse(ctx, gin.H{
		"list":     list,
		"total":    count,
		"page":     req.Page,
		"pageSize": req.PageSize,
		"notMoney": NotMoney,
		"money":    Money,
	})
}

// Detail 详情api
func (o *OrderApi) Detail(ctx *gin.Context) {
	var req core.GetById
	_ = ctx.Bind(&req)
	if data, e := o.svc.Detail(req.ID); e != nil {
		web.FailResponse(ctx, e, "服务异常")
	} else {
		web.SuccessResponse(ctx, data)
	}
}

// Update 修改
func (o *OrderApi) Update(ctx *gin.Context) {
	var req model.Order
	_ = ctx.Bind(&req)

	if err := o.svc.Update(req); err != nil {
		web.FailResponse(ctx, err, "")
		return
	} else {
		web.SuccessResponse(ctx, nil)
	}
}

// Create 创建
func (o *OrderApi) Create(ctx *gin.Context) {
	var (
		req model.Order
	)
	_ = ctx.Bind(&req)

	//检查客户是否存在
	var customerInfo model.Customer
	if orm.GetDb().Where("id = ?", req.CustomerId).First(&customerInfo).Error != nil {
		web.FailResponse(ctx, errors.New("客户不存在"), "客户不存在")
		return
	}

	if req.UserId == 0 {
		req.UserId = uint(service2.GetUserID(ctx))
	}

	if userInfo, err := orm.Detail[layerModel.ServiceUser](int(req.UserId), "Role"); err != nil {
		web.FailResponse(ctx, err, "服务异常")
		return
	} else {
		req.DepId = userInfo.DepId
	}
	req.OrderAdds = nil
	req.ChannelId = customerInfo.ChannelId

	if err := o.svc.Create(req); err != nil {
		web.FailResponse(ctx, err, "")
		return
	} else {
		web.SuccessResponse(ctx, nil)
	}
}

// Delete 删除
func (o *OrderApi) Delete(ctx *gin.Context) {
	var req core.GetById
	_ = ctx.Bind(&req)
	if err := o.svc.Delete(req.ID); err != nil {
		web.FailResponse(ctx, err, "")
		return
	} else {
		web.SuccessResponse(ctx, nil)
	}
}
